package com.kang.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.kang.dao.AuditItemMapper;
import com.kang.dao.AuditMapper;
import com.kang.dao.ItemDetailMapper;
import com.kang.dao.PurchaseOrderItemMapper;
import com.kang.dao.PurchaseOrderMapper;
import com.kang.dao.PurchaseRequestItemMapper;
import com.kang.dao.PurchaseRequestMapper;
import com.kang.dao.ReturnRequestItemMapper;
import com.kang.dao.ReturnRequestMapper;
import com.kang.pojo.Audit;
import com.kang.pojo.AuditFlow;
import com.kang.pojo.AuditFlowItem;
import com.kang.pojo.AuditItem;
import com.kang.pojo.AuditRecord;
import com.kang.pojo.PurchaseOrder;
import com.kang.pojo.PurchaseOrderItem;
import com.kang.pojo.PurchaseRequest;
import com.kang.pojo.ReturnRequest;
import com.kang.pojo.ReturnRequestItem;
import com.kang.service.AuditService;
import com.vonechina.entity.page.ApproveByMeAuditPage;
import com.vonechina.entity.page.AuditPage;
import com.vonechina.entity.page.MySubmittedAuditPage;

/**
 * 审批服务层实现类
 * 
 * @author zs614
 *
 */
@Service("AuditService")
public class AuditServiceImpl implements AuditService {
	/**
	 * 审核节点持久层
	 */
	@Resource
	private AuditItemMapper audits;
	/**
	 * 审核记录持久层
	 */
	@Resource
	private AuditMapper am;
	/**
	 * 采购订单持久层
	 */
	@Resource
	private PurchaseOrderMapper purchaseOrderMapper;
	/**
	 * 退货申请持久层
	 */
	@Resource
	private ReturnRequestMapper returnRequestMapper;
	/**
	 * 采购申请持久层
	 */
	@Resource
	private PurchaseRequestMapper purchaseRequestMapper;
	/**
	 * 采购申请物品信息持久层
	 */
	@Resource
	private PurchaseRequestItemMapper purchaseRequestItemMapper;
	/**
	 * 采购订单物品信息持久层
	 */
	@Resource
	private PurchaseOrderItemMapper purchaseOrderItemMapper;
	/**
	 * 退货申请物品信息持久层
	 */
	@Resource
	private ReturnRequestItemMapper returnRequestItemMapper;
	/**
	 * 物品批次持久层
	 */
	@Resource
	private ItemDetailMapper itemDetailMapper;

	/**
	 * 添加审批记录
	 * 
	 * @param audit
	 *            审批记录实体类
	 * @return
	 */
	@Override
	public int addAudit(Audit audit) {
		int reback = 0;
		audit.setCurrentLevel(1);
		audit.setStatus("0");
		audit.setLastProcessingTime(new Date());
		AuditFlow auditflow = new AuditFlow();
		auditflow = audits.selectAuditFlow(audit.getAuditType());
		List<AuditFlowItem> list = audits.selectAuditFlowItem(auditflow.getAuditFlowID());
		audit.setLevelNumber(list.size());
		audits.insertdataaudit(audit);// 插入
		for (int i = 0; i < list.size(); i++) {
			AuditItem audititem = new AuditItem();
			audititem.setAuditID(audit.getAuditID());
			audititem.setLevel(list.get(i).getLevel());
			audititem.setRoleID(list.get(i).getRoleID());
			audititem.setAuditUsernNumber(list.get(i).getPassPersonNumber());
			audititem.setAuditPassUserID("");
			audititem.setAuditRejectUserID("");
			audititem.setConditions("");
			audititem.setStatus("" + list.get(i).getStatus() + "");
			audititem.setLastPersonID(0);
			audititem.setLastProcessingTime(new Date());
			reback = audits.insertdataaudititem(audititem);// 插入
		}
		return reback;
	}

	/**
	 * 分页查询审批
	 * 
	 * @param auditPage
	 *            搜索条件实体类
	 * @return
	 */
	@Override
	public List<Map<String, Object>> listAudit(AuditPage auditPage) {
		auditPage.setRows(audits.getselectdataCount(auditPage));
		List<Map<String, Object>> list = audits.getselectdata(auditPage);

		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).get("auditPassUserID") != null) {
				String[] sourceStrArray = list.get(i).get("auditPassUserID").toString().split(",");
				String rolenames = "";
				// 查询通过审核人
				for (int j = 0; j < sourceStrArray.length; j++) {
					if (sourceStrArray[j].length() > 0) {
						String str = audits.selectUserRoles(Integer.parseInt(sourceStrArray[j]));
						rolenames = rolenames + "" + str + ",";
					}
				}
				// 查询拒绝审核人
				String[] auditRejectUserIDs = list.get(i).get("auditRejectUserID").toString().split(",");
				String auditRejectUsername = "";
				if (auditRejectUserIDs.length > 0) {
					for (int k = 0; k < auditRejectUserIDs.length; k++) {
						if (auditRejectUserIDs[k].length() > 0) {
							String str = audits.selectUserRoles(Integer.parseInt(auditRejectUserIDs[k]));
							auditRejectUsername = auditRejectUsername + "" + str + ",";
						}
					}
				}
				// 查询当前审核人
				String listnames = "";
				List<String> listNames = audits.selectlistnames(Integer.parseInt(list.get(i).get("roleID").toString()));
				if (listNames.size() > 0) {
					for (int l = 0; l < listNames.size(); l++) {
						listnames = listnames + "" + listNames.get(l) + ",";
					}
				}
				//
				if (rolenames.length() > 0) {
					rolenames = rolenames.substring(0, rolenames.length() - 1);
				}
				if (auditRejectUsername.length() > 0) {
					auditRejectUsername = auditRejectUsername.substring(0, auditRejectUsername.length() - 1);
				}
				if (listnames.length() > 0) {
					listnames = listnames.substring(0, listnames.length() - 1);
				}

				list.get(i).put("auditPassUsername", rolenames);
				list.get(i).put("auditRejectUsername", auditRejectUsername);
				list.get(i).put("listnames", listnames);
				int auditType = (int) list.get(i).get("auditType");
				int sourceID = (int) list.get(i).get("sourceID");
				if (auditType == 1) {
					PurchaseRequest request = purchaseRequestMapper.selectByPrimaryKey(sourceID);
					list.get(i).put("applicationNo", request.getApplicationNo());
					list.get(i).put("loginName", request.getApplicantName());
				} else if (auditType == 2) {
					PurchaseOrder order = purchaseOrderMapper.selectOrderById(sourceID);
					list.get(i).put("applicationNo", order.getOrderNumber());
					list.get(i).put("loginName", order.getCreatePersonName());

				} else if (auditType == 3) {
					ReturnRequest request = returnRequestMapper.selectByPrimaryKey(sourceID);
					list.get(i).put("applicationNo", request.getApplicationNo());
					list.get(i).put("loginName", request.getCreatePersonName());
				}
			}
		}
		return list;
	}

	/**
	 * 拒绝审批
	 * 
	 * @param id
	 *            审批ID
	 * @param userID
	 *            用户ID
	 * @return
	 */
	@Override
	public int rejectapproveRequest(int id, int userID) {
		// 修改之前将拒绝用户id查出
		Map<String, Object> info = audits.selectCurrentlevelInfo(id);
		String auditRejectUserID = (String) info.get("auditRejectUserID");
		int auditID = ((Integer) info.get("auditID")).intValue();
		int auditType = ((Integer) info.get("auditType")).intValue();
		int sourceID = Integer.parseInt(info.get("sourceID").toString());
		if (!"".equals(auditRejectUserID)) {
			auditRejectUserID += ",";
		}
		auditRejectUserID += userID;
		audits.saveRejectUserID(id, userID, auditRejectUserID);
		audits.setAuditItemStatus(id, 2);
		audits.updateAuditStatus(auditID, 2);
		audits.insertauditrecord(datahandle(id, 1, new Date(), userID));// 插入一条审批记录
		if (auditType == 1) {// 采购申请
			purchaseRequestMapper.updateStatus(sourceID, 4);
		} else if (auditType == 2) {// 采购订单
			purchaseOrderMapper.updateStatus(sourceID, 4);
			List<PurchaseOrderItem> items = purchaseOrderItemMapper.listItemForOrder(sourceID);
			for (PurchaseOrderItem item : items) {
				purchaseRequestItemMapper.updateStatus(item.getSourceID(), 0);

			}
		} else if (auditType == 3) {// 退货订单
			returnRequestMapper.updateStatus(sourceID, 4);
			List<ReturnRequestItem> items = returnRequestItemMapper.listByReturnRequestID(sourceID);
			for (ReturnRequestItem item : items) {
				itemDetailMapper.addStock(item.getSourceID(), item.getNumber());
			}
		}

		return 1;
	}

	/**
	 * 通过审批
	 * 
	 * @param id
	 *            审批ID
	 * @param userID
	 *            用户ID
	 * @return
	 */
	@Override
	public int passapproveRequest(int id, int userID) {
		// int Result=0;
		// 先查出审批总级别是多少
		Map<String, Object> info = audits.selectCurrentlevelInfo(id);
		int levelNumber = Integer.parseInt(info.get("levelNumber").toString());
		int currentLevel = Integer.parseInt(info.get("currentLevel").toString());// 当前级别
		int sourceID = Integer.parseInt(info.get("sourceID").toString());
		int auditUsernNumber = ((Integer) info.get("auditUsernNumber")).intValue();
		int auditID = ((Integer) info.get("auditID")).intValue();
		int auditType = ((Integer) info.get("auditType")).intValue();
		String auditPassUserID = info.get("auditPassUserID").toString().trim();
		if (!"".equals(auditPassUserID)) {
			auditPassUserID += ",";
		}
		auditPassUserID += userID;
		audits.savePassUserID(id, auditPassUserID);
		audits.insertauditrecord(datahandle(id, 0, new Date(), userID));// 插入一条审批记录
		if (auditPassUserID.split(",").length < auditUsernNumber) {
			return 1;
		}
		audits.setAuditItemStatus(id, 1);

		if (currentLevel >= levelNumber) {
			audits.updateAuditStatus(auditID, 1);

			if (auditType == 1) {// 采购申请
				purchaseRequestMapper.updateStatus(sourceID, 3);

			} else if (auditType == 2) {// 采购订单
				purchaseOrderMapper.updateStatus(sourceID, 3);
			} else if (auditType == 3) {// 退货申请
				returnRequestMapper.updateStatus(sourceID, 3);
			}
			return 1;
		}
		return audits.updateAuditCurrentLevel(auditID, currentLevel + 1);
	}

	/**
	 * 查询我提交的审批
	 * 
	 * @param page
	 *            搜索条件实体类
	 * @return
	 */
	@Override
	public List<Audit> listMySubmittedAudit(MySubmittedAuditPage page) {
		page.setRows(am.countMySubmittedAudit(page));
		List<Audit> list = am.listMySubmittedAudit(page);
		if (list != null) {
			for (Audit a : list) {
				if (a.getAuditType() == 1) {
					PurchaseRequest request = purchaseRequestMapper.selectByPrimaryKey(a.getSourceID());
					a.setApplicationNo(request.getApplicationNo());
				} else if (a.getAuditType() == 2) {
					PurchaseOrder order = purchaseOrderMapper.selectOrderById(a.getSourceID());
					a.setApplicationNo(order.getOrderNumber());
				} else if (a.getAuditType() == 3) {
					ReturnRequest request = returnRequestMapper.selectByPrimaryKey(a.getSourceID());
					a.setApplicationNo(request.getApplicationNo());
				}
				if (a.getAuditPassUserID() != null && a.getAuditPassUserID().trim().length() > 0)
					a.setPassUserName(am.selectUserNameIn(a.getAuditPassUserID()));
				if (a.getAuditRejectUserID() != null && a.getAuditRejectUserID().trim().length() > 0)
					a.setRejectUserName(am.selectUserNameIn(a.getAuditRejectUserID()));
			}
		}
		return list;
	}

	// 设置对象
	private AuditRecord datahandle(int id, int j, Date date, int userID) {
		AuditRecord auditRecord = new AuditRecord();
		// auditRecord.setId(i);
		auditRecord.setAuditItemID(id);
		auditRecord.setResult(j);
		auditRecord.setCreateTime(date);
		auditRecord.setUserID(userID);
		return auditRecord;
	}

	/**
	 * 查询我审批的
	 * 
	 * @param page
	 *            搜索条件实体类
	 * @return
	 */
	@Override
	public List<Audit> listApproveByMe(ApproveByMeAuditPage page) {
		page.setRows(am.countApproveByMe(page));
		List<Audit> list = am.listApproveByMe(page);
		if (list != null) {
			for (Audit a : list) {
				if (a.getAuditType() == 1) {
					PurchaseRequest request = purchaseRequestMapper.selectByPrimaryKey(a.getSourceID());
					a.setApplicationNo(request.getApplicationNo());
					a.setApplicantName(request.getApplicantName());
				} else if (a.getAuditType() == 2) {
					PurchaseOrder order = purchaseOrderMapper.selectOrderById(a.getSourceID());
					a.setApplicationNo(order.getOrderNumber());
					a.setApplicantName(order.getCreatePersonName());
				} else if (a.getAuditType() == 3) {
					ReturnRequest request = returnRequestMapper.selectByPrimaryKey(a.getSourceID());
					a.setApplicationNo(request.getApplicationNo());
					a.setApplicantName(request.getCreatePersonName());
				}
			}
		}
		return list;
	}

	/**
	 * 查询审批条数
	 * 
	 * @param auditPage
	 *            搜索条件实体类
	 * @return
	 */
	@Override
	public int countAudit(AuditPage auditPage) {
		return audits.getselectdataCount(auditPage);
	}

	/**
	 * 获取桌面审批总数记录
	 * 
	 * @param userID
	 *            登录用户ID
	 * @return
	 */
	@Override
	public Map<String, String> getdatarRecoardnumber(int userID) {
		// 待我审批的记录
		Map<String, String> mapzz = new HashMap<String, String>();
		AuditPage page = new AuditPage();
		page.setUserID(userID);
		page.setAuditType(1);
		mapzz.put("applynum", "" + audits.countNeedApproveByMe(page));
		page.setAuditType(2);
		mapzz.put("purchasenum", "" + audits.countNeedApproveByMe(page));
		page.setAuditType(3);
		mapzz.put("returnRequestAuditOfMe", "" + audits.countNeedApproveByMe(page));

		// 我审核的
		mapzz.put("passpur", "" + audits.countApproveByMe(userID, 1));
		mapzz.put("passodrer", "" + audits.countApproveByMe(userID, 2));
		mapzz.put("passreturn", "" + audits.countApproveByMe(userID, 3));

		// 我的通过申请
		Map<String, Object> list = audits.getpassapplynumber(userID);
		mapzz.put("purnum", "" + list.get("purnum"));
		mapzz.put("ordernum", "" + list.get("ordernum"));
		mapzz.put("returnnum", "" + list.get("returnnum"));

		// 我的拒绝申请
		Map<String, Object> reject = audits.getrejectapplynumber(userID);
		mapzz.put("purnumreject", "" + reject.get("purnum"));
		mapzz.put("ordernumreject", "" + reject.get("ordernum"));
		mapzz.put("returnnumreject", "" + reject.get("returnnum"));

		return mapzz;
	}
}
